package com.landleaf.smarthome.db.dao;

import com.landleaf.smarthome.db.manager.DbManager;

import org.greenrobot.greendao.AbstractDao;

import java.util.ArrayList;
import java.util.List;

/**
 * When I wrote this, only God and I understood what I was doing
 * Now, God only knows
 * Created by 海航
 * 2019/9/3
 * 功能描述:
 */
public class BaseDaoHelper<T extends AbstractDao, R> {
    protected DbManager mManager;
    public BaseDaoHelper() {
        mManager = DbManager.getInstance();

    }
    public BaseDaoHelper(T t) {
        mManager = DbManager.getInstance();
        this.dao = t;
    }

    protected T dao;

    /**
     * 完成Bean记录的插入
     *
     * @return
     */

    public boolean insertOneData(R model) {
        boolean flag = dao.insertOrReplace(model) == -1 ? false : true;
        dao.detachAll();
        return flag;
    }

    /**
     * 删除所有数据
     *
     * @return
     */

    public void deleteAll() {
        dao.deleteAll();
        dao.detachAll();
    }

    /**
     * 完成Bean记录的插入
     *
     * @return
     */

    public void insertDatas(List<R> models) {
        if (models != null && models.size() > 0) {
            dao.insertOrReplaceInTx(models);
            dao.detachAll();
        }

    }

    /**
     * 查找所有数据
     *
     * @return
     */

    public List<R> findAllData() {
        List<R> list = dao.loadAll();
        if (list == null || list.size() == 0) {
            return new ArrayList<R>();
        }
        return list;
    }

    /**
     * 修改一条数据
     *
     * @param
     * @return
     */

    public boolean updateModel(R model) {
        boolean flag = false;
        try {
            dao.update(model);
            dao.detachAll();
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;

    }

    public void deleteOneData(long id) {
        dao.deleteByKey(id);
        dao.detachAll();
    }

    public void deleteOneData(R model) {
        dao.delete(model);
        dao.detachAll();
    }

    public long getDataCount() {
        return dao.count();
    }
}
